using Microsoft.AspNetCore.Mvc;
using SPI.AgentServer.Services.Cache;
using Swashbuckle.AspNetCore.Annotations;

namespace SPI.AgentServer.Controllers;

/// <summary>
/// 缓存管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class CacheController : ControllerBase
{
    private readonly IQueryCacheService _cacheService;
    private readonly ILogger<CacheController> _logger;

    public CacheController(
        IQueryCacheService cacheService,
        ILogger<CacheController> logger)
    {
        _cacheService = cacheService;
        _logger = logger;
    }

    /// <summary>
    /// 获取缓存统计信息
    /// </summary>
    [HttpGet("stats")]
    [SwaggerOperation(Summary = "获取缓存统计信息")]
    public async Task<IActionResult> GetStats()
    {
        var stats = await _cacheService.GetStatsAsync();
        
        return Ok(new
        {
            success = true,
            data = stats,
            message = $"缓存命中率：{stats.HitRate:F2}%"
        });
    }

    /// <summary>
    /// 清除所有缓存
    /// </summary>
    [HttpPost("clear")]
    [SwaggerOperation(Summary = "清除所有查询缓存")]
    public async Task<IActionResult> ClearAll()
    {
        await _cacheService.ClearAllAsync();
        
        _logger.LogInformation("已清除所有查询缓存");
        
        return Ok(new
        {
            success = true,
            message = "所有缓存已清除"
        });
    }

    /// <summary>
    /// 清除指定查询的缓存
    /// </summary>
    [HttpDelete]
    [SwaggerOperation(Summary = "清除指定查询的缓存")]
    public async Task<IActionResult> Remove([FromQuery] string query, [FromQuery] string? databaseName = null)
    {
        if (string.IsNullOrWhiteSpace(query))
        {
            return BadRequest(new { success = false, message = "查询内容不能为空" });
        }

        await _cacheService.RemoveAsync(query, databaseName);
        
        return Ok(new
        {
            success = true,
            message = $"已清除缓存：{query}"
        });
    }
}





